import { homePage, couponList, getCoupon, thirdLogin, userInfo, getActivity, getGoods, getCate} from '../../../services/API'
import { remainTime } from '../../../utils/utils';
import { auth } from '../../../services/auth';
import * as wxAPI from '../../../services/wxAPI';
const app = getApp();
const template = require('../../TEMPLATE/tabBar/tabBar.js');

Page({
  data: {
    http: app.http,
    host: app.host,
    article: [],
    first: [],
    second: [],
    third: [],
    items: [],
    cates:[],
    cate:[],
    remai: [],
    tuijian: [],
    team: '',
    miaosha: [],
    banners: [],
    xinpin:[],
    h: '',
    m: '',
    s: '',
    endDate2: '',

    coupons: [],
    navTabs: [      
      {
        src: '/images/pintuan.png',
        name: '拼团专区',
        url: "/pages/TEAM/team/team"
      },
      {
        src: '/images/youhuiquan.png',
        name: '优惠券',
        url: "/pages/USER/notused/notused"    
      }
    ],
    special: {
      showSpecial: false,
      list: ''
    },
    loading: false,
    homeLoading: false
  },
  onLoad() {
    let special = this.data.special;

    var that = this
    getCate().then(({ status, result, msg }) => {
      if (status == 1) {
        console.log(result)
        that.setDatas(result.category, 0)
        that.setData({
          cate: result.category
        })
      }
    }) 
    // getActivity()
    //   .then(({ status, result, msg }) => {
    //     if (status == 1) {
    //       special.list = result;
    //       this.setData({
    //         special
    //       })
    //       app.specialList = result;
    //       console.log(this.data.special, "special");
    //     } else {
    //       app.wxAPI.alert(msg);
    //     }
    //   })
    this.setData({
      loading: false,
      homeLoading: false
    })

    template.tabbar("tabBar", 0, this);
    this.setData({
      homeLoading: true
    })
    this.setData({
      loading: true
    })
    app.wxAPI.showLoading('加载中...');

    this.getHomePage();
    this.getCoupons();

    let userInfo = '';
    wxAPI.getSetting()
      .then((res) => {
        if (~res.indexOf('scope.userInfo')) {
          wxAPI.getUserInfo()
            .then((res) => {
              userInfo = res.userInfo;
              return wxAPI.login()
            })
            .then((res) => {
              return thirdLogin({
                code: res.code,
                from: 'miniapp',
                nickname: userInfo.nickName,
                head_pic: userInfo.avatarUrl
              })
            })
            .then(({ status, result, msg }) => {
              if (status == 1) {
                result.nickname = userInfo.nickName;
                result.head_pic = userInfo.avatarUrl;
                app.userInfo = result;
                app.token = result.token;
                this.getCoupons();
              }
            })
          return;
        }
      })
    this.countTime()
  },
  onShow() {
    userInfo({
      token: app.token
    })
    .then(({
      status,
      result,
      msg
    }) => {
      
      // getApp().userInfo = result;
      getApp().userInfo.user_id = result.user_id
      console.log('huanc', result.user_id);
      wx.setStorageSync('id', result.user_id)
      this.setData({
        userInfo: app.userInfo,
        userid: result.user_id
      });
    })
  },
  getHomePage() {
    homePage().then(({ status, result, msg }) => {
      this.setData({
        homeLoading: false
      })
      let loading = this.data.loading;
      let homeLoading = this.data.homeLoading;
      if (!loading && !homeLoading) {
        app.wxAPI.hideLoading();
      }
      if (status == 1) {
        const hour = new Date(result.start_time * 1000).getHours();
        const endTime = result.end_time;
        let newEndTime = result.now_time;
        let disTime = endTime - newEndTime;

        let timer = setInterval(() => {
          disTime--;
          let finish = remainTime(disTime);
          if (finish == '结束') {
            timer.clearInterval();
            finish = '00：00：00';
          }
          this.setData({
            time: finish
          })
        }, 1000)
        if (result.tuijian.length !== 0) {
          for (let i in result.tuijian) {
            result.tuijian[i].sales_sum = parseInt(result.tuijian[i].num) + parseInt(result.tuijian[i].sales_sum)
          }
        }
        if (result.remai.length !== 0) {
          for (let i in result.remai) {
            result.remai[i].sales_sum = parseInt(result.remai[i].num) + parseInt(result.remai[i].sales_sum)
          }
        }
        this.setData({
          banners: result.banner,
          // huodong: result.second,
          // first: result.first,
          // second: result.second,
          // third: result.third,
          remai: result.remai,
          tuijian: result.tuijian,
          team: result.team,
          xinpin:result.xinpin,
          miaosha: result.miaosha
          // article: result.article,
          // video: result.video,
          // startHour: hour
        })
      } else {
        app.wxAPI.alert(msg);
      }
    })
  },

  setDatas(item, index) {
    let i = index ? index : 0;
    if (i < item.length) {
      getGoods({ category_id: item[i].id }).then(({ status, result, msg }) => {
        if (status == 1) {
          this.data.items.push(result)
          i++;
          this.setDatas(item, i)
        }
      })
    } else {
      var cates = this.data.cate
      var htitem = this.data.items
      for (var x = 0; x < cates.length; x++) {
        cates[x].hotitems = htitem[x]
      }
      this.setData({
        cates: cates
      })
    }
  },
  getCoupons() {
    couponList()
      .then(({ status, result, msg }) => {
        this.setData({
          loading: false
        })
        let loading = this.data.loading;
        let homeLoading = this.data.homeLoading;
        if (!loading && !homeLoading) {
          app.wxAPI.hideLoading();
        }
        if (status == 1) {
          (result || []).forEach((item) => {
            item._money = parseInt(item.money);
            item._condition = parseInt(item.condition);
          })
          let coupons = (result || []).filter((item) => {
            // return true;
            return item.isget || item.isget != 1;
          })
          this.setData({ coupons })
        } else {
          app.wxAPI.alert(msg);
        }                                
      })
  },
  onblur(e) {
    this.setData({
      keyword: e.detail.value
    })
  },
  oninput(e) {
    let keyword = e.detail.value
    if (keyword != '') {
      this.setData({
        isEmpt: true,
        keyword
      })
    } else {
      this.setData({
        isEmpt: false
      })
    }
    return keyword.trim()
  },
  empt() {
    setTimeout(() => {
      this.setData({
        keyword: '',
        isEmpt: false
      })
    }, 50)
  },
  search() {
    const keyword = this.data.keyword;
    if (keyword) {
      wx.navigateTo({
        url: `/pages/HOME/searchResult/searchResult?keyword=${keyword}`
      })
    }
  },
  tabList(e) {
    const index = e.currentTarget.dataset.index;
    const list = this.data.navTabs;
    if(!list[index].url) {
      app.wxAPI.alert('该功能未开启！');
      return;
    } else {
      wx.navigateTo({
        url: list[index].url
      })
    }
  },
  onShareAppMessage(res) {
    return {
      title: '艺传天下艺考专家 ',
      path: '/pages/HOME/home/home'
    }
  },
  receiveCoupon(e) {
    const id = e.currentTarget.dataset.id;
    let token = app.token;
    if (!token) {
      app.wxAPI.alert('未登录!')
        .then(() => {
          wx.reLaunch({
            url: '/pages/USER/user/user?from=pages/HOME/home/home'
          })
        })
      return
    } else {
      getCoupon({ coupon_id: id })
        .then(({ status, result, msg }) => {
          if (status == 1) {
            app.wxAPI.alert('领取成功！')
              .then(() => {
                this.getCoupons();
              })
          } else if (status == 0) {
            app.wxAPI.alert(msg)
          }
        })
    }   
  },
  //专题点击
  clickSpecial() {
    template.tabbar("tabBar", 2, this);
    let special = this.data.special;

    if (special.list.length == 0) {
      app.wxAPI.alert('专题暂未开启！')
        .then(() => {
          template.tabbar("tabBar", 0, this);
        })
      return;
    }
    special.showSpecial = true;
    this.setData({ special });
  },
  navigatorTo(e) {
    let url = e.currentTarget.dataset.url;
    const id = e.currentTarget.dataset.id;
    if (!url) {
      url = `/pages/SPECIAL/special/special?id=${id}`
    }
    wx.navigateTo({
      url: url
    })
    this.closePopup();
    template.tabbar("tabBar", 0, this);
  },
  closePopup() {
    let special = this.data.special;
    special.showSpecial = false;
    this.setData({ special });
    template.tabbar("tabBar", 0, this);
  },
  countTime() {
    var that = this;
    var date = new Date();
    var now = date.getTime();
    const end = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1);
    // var endDate = new Date(that.data.endDate2);//设置截止时间
    // var end = date.getDate() ;
    var leftTime = end - now; //时间差                              
    var d, h, m, s, ms;
    if (leftTime >= 0) {
      d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      m = Math.floor(leftTime / 1000 / 60 % 60);
      s = Math.floor(leftTime / 1000 % 60);
      ms = Math.floor(leftTime % 1000);
      ms = ms < 100 ? "0" + ms : ms
      s = s < 10 ? "0" + s : s
      m = m < 10 ? "0" + m : m
      h = h < 10 ? "0" + h : h
      that.setData({
        h, m, s
      })
      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(that.countTime, 100);
    } else {
      this.setData({
        h: '00', m: '00', s: '00'
      })
    }

  }
})